package com.tg.app.activity.tools;

import android.app.ActionBar;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.alibaba.fastjson.JSON;
import com.tg.app.R;
import com.base.BaseActivity;
import com.tange.core.backend.service.api.CoreApiUrl;
import com.tange.base.toolkit.ClipboardUtils;
import com.tange.core.backend.service.http.ClientObserver;
import com.tange.core.backend.service.http.CoreHttpClient;
import com.tange.core.backend.service.api.TGCoreServiceApi;
import com.tg.data.http.entity.ServerHub;
import com.tg.network.socket.detection.DeviceUtils;
import com.tg.network.socket.detection.task.TaskCallBack;
import com.tg.network.socket.detection.task.TraceTask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetworkDetectionActivity extends BaseActivity implements TaskCallBack {
    TextView resultTextView;
    private List<String> url = new ArrayList();
    public final  static String  INTENT_URL ="NetworkDetection_urls";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_network_detection);
        hideActionBar();

        resultTextView = findViewById(R.id.tv_result);
        findViewById(R.id.bt_trace).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resultTextView.setText("");
                doDetection();
            }
        });
        url.add("http://www.baidu.com");
        List<String> list = getIntent().getStringArrayListExtra(INTENT_URL);
        if (list!=null){
            url.addAll(list);
        }
        doDetection();
        ActionBar actionBar =  getActionBar();
        if (actionBar!=null){
            actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
        }
        findViewById(R.id.back_toolbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    @Override
    protected void initView() {

    }

    private void doDetection(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(CoreApiUrl.TG_HUB)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(CoreHttpClient.getOkHttpClient())
                .build();
        TGCoreServiceApi api = retrofit.create(TGCoreServiceApi.class);
        HashMap<String, String> map = new HashMap<>();
        map.put("source", "app");


        api.getHub(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<ServerHub>() {

                    @Override
                    protected void onSuccess(ServerHub content) {
                        if (content != null) {
                            resultTextView.setText(JSON.toJSONString(content));
                            resultTextView.append("\n");
                        }
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        TraceTask traceTask = new TraceTask(getApplication(),
                                url, NetworkDetectionActivity.this);
                        traceTask.setAppVersion(DeviceUtils.getVersion(getBaseContext()));
                        traceTask.setAppName(DeviceUtils.getAppName(getBaseContext()));
                        traceTask.setAppCode(DeviceUtils.getVersionCode(getBaseContext())+"");
                        traceTask.setDeviceId(DeviceUtils.getAndroidID(getBaseContext()));
                        traceTask.setAlwaysPing(false); //是否永远进行Ping，如果是false，则根据当前网络环境判断是否要Ping
                        traceTask.doTask();
                    }
                });


    }

    @Override
    public void onUpdated(String log) {
        resultTextView.append(log);
    }

    @Override
    public void onFinish(String log) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        final AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("诊断结束")
                .setMessage("可复制诊断信息到剪切板")
                .setCancelable(false)
                .setPositiveButton("复制", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String info = resultTextView.getText().toString();
                        ClipboardUtils.copyToClipboard(getBaseContext(), info);
                        Toast.makeText(getApplicationContext(), "复制诊断信息成功!", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .create();

        if (!isFinishing() && !isDestroyed()) {
            try {
                dialog.show();
            } catch (Throwable ex) {
                // ignore
            }
        }
    }

    @Override
    public void onFailed(Exception e) {
        resultTextView.append("诊断失败:" + e.getMessage());
        Toast.makeText(this, "诊断失败:" + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}